package net.itren.jetpackdemo.utils

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type
import java.util.*

object GsonUtil {
    private var gson: Gson? = null

    /**
     * 转成json
     *
     * @param object
     * @return
     */
    fun gsonString(ob: Any?): String? {
        var gsonString: String? = null
        if (gson != null) {
            gsonString = gson!!.toJson(ob)
        }
        return gsonString
    }

    /**
     * 转成bean
     *
     * @param gsonString
     * @param cls
     * @return
     */
    fun <T> gsonToBean(gsonString: String?, cls: Class<T>?): T? {
        var t: T? = null
        if (gson != null) {
            t = gson!!.fromJson(gsonString, cls)
        }
        return t
    }

    /**
     * 转成list
     *
     * @param gsonString
     * @param cls
     * @return
     */
    fun <T> gsonToList(gsonString: String?, cls: Class<T>?): List<T>? {
        var list: List<T>? = null
        if (gson != null) {
            list = gson!!.fromJson(gsonString, object : TypeToken<List<T>?>() {}.type)
        }
        return list
    }

    /**
     * 转成list
     *
     * @return
     */
    fun <T> stringToArray(s: String?, clazz: Class<Array<T>?>?): List<T> {
        val arr = Gson().fromJson(s, clazz)!!
        return Arrays.asList(*arr) //or return Arrays.asList(new Gson().fromJson(s, clazz)); for a one-liner
    }

    /**
     * 转成list中有map的
     *
     * @param gsonString
     * @return
     */
    fun <T> gsonToListMaps(gsonString: String?): List<Map<String, T>>? {
        var list: List<Map<String, T>>? = null
        if (gson != null) {
            list = gson!!.fromJson(
                gsonString,
                object : TypeToken<List<Map<String?, T>?>?>() {}.type
            )
        }
        return list
    }

    /**
     * 转成map的
     *
     * @param gsonString
     * @return
     */
    fun <T> gsonToMaps(gsonString: String?): Map<String, T>? {
        var map: Map<String, T>? = null
        if (gson != null) {
            map = gson!!.fromJson(gsonString, object : TypeToken<Map<String?, T>?>() {}.type)
        }
        return map
    }

    fun fromJson(s: String?, type: Type?): Any {
        return gson!!.fromJson(s, type)
    }

    init {
        if (gson == null) {
            gson = Gson()
        }
    }
}